package com.zouxin.zouxin_slidecard;

import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.RecyclerView;

public class SlideCardLayoutManager extends RecyclerView.LayoutManager {
    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    //布局
    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        //ViewHolder回收复用
        detachAndScrapAttachedViews(recycler);

        int bottomPostion;
        int itemCount = getItemCount();
        if (itemCount<CardConfig.MAX_SHOW_COUNT){
            bottomPostion=0;
        }else {
            //布局了四张卡牌  ---4,5,6,7
            bottomPostion = itemCount - CardConfig.MAX_SHOW_COUNT;
        }

        for (int i = bottomPostion; i < itemCount; i++) {
            //复用
            View view = recycler.getViewForPosition(i);
            addView(view);

            measureChildWithMargins(view,0,0);

            //layoutChunk --> layoutDecoratedWithMargins
            //getDecoratedMeasuredWidth获取除了获取宽高以外，还会把分割线加进来
            int withSpace = getWidth() - getDecoratedMeasuredWidth(view);
            int heightSpace = getHeight() - getDecoratedMeasuredHeight(view);

            //布局
            layoutDecoratedWithMargins(view,withSpace/2,
                    heightSpace/2,
                    withSpace/2+getDecoratedMeasuredWidth(view),
                    heightSpace/2+getDecoratedMeasuredHeight(view));

            int level=itemCount-i-1;
            if (level>0){
                if (level<CardConfig.MAX_SHOW_COUNT-1) {
                    view.setTranslationY(CardConfig.TRANS_Y_GAP * level);
                    view.setScaleX(1 - CardConfig.SCALE_GAP * level);
                    view.setScaleY(1 - CardConfig.SCALE_GAP * level);
                }else {
                    //最下面的view与前一个view布局一样
                    view.setTranslationY(CardConfig.TRANS_Y_GAP * (level-1));
                    view.setScaleX(1 - CardConfig.SCALE_GAP * (level-1));
                    view.setScaleY(1 - CardConfig.SCALE_GAP * (level-1));
                }
            }
        }
    }
}
